package web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import vo.SourceCategory;
import vo.Topic;
import vo.TopicSource;
import vo.User;
import vo.UserTopic;
import vo.Warn;
import business.SourceCategoryService;
import business.SourceService;
import business.TopicService;
import business.TopicSourceService;
import business.UserService;
import business.UserTopicService;
import business.WarnService;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("unchecked")
public class TopicAction implements Preparable {
	private TopicService service;
	private UserService userService;
	private SourceService sourceService;
	private TopicSourceService topicSourceService;
	private SourceCategoryService sourceCategoryService;
	private WarnService warnService;
	private UserTopicService userTopicService;

	private List<Topic> topics;
	private List<SourceCategory> sourceCategories;
	private ArrayList<String> delIds = new ArrayList<String>();

	private String name;
	// private long sourceCategory;
	private String description;

	private String include;
	private String optional;
	private String exclude;
	private int isNegative;
	private int isWarn;
	private int withinPublishedTime;
	// private String userString;

	private String selectedSourceCategory;
	private String selectedIsWarn;
	private String selectedIsNegative;
	private String selectedWithinPublishedTime;

	private int curPage;
	private int totalPage;
	private int pageSize = 5;

	private User curUser;

	// 更新topic
	private int topicId;
	private String sourceCategoryName;

	private List<String> names;
	ArrayList<SourceCategory> filters;

	// 检索参数
	private String userName;
	private String expireDttm;

	public String listTopic() {
		System.out.println("list Topic");
		// this.sourceCategories =
		// sourceCategoryService.getAllSourceCategories();

		// 取出检索条件
		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		name = (String) session.get("topicName");
		userName = (String) session.get("topicUserName");
		expireDttm = (String) session.get("topicExpireDttm");

		System.out.println("name:" + name);
		System.out.println("userName:" + userName);
		System.out.println("expireDttm:" + expireDttm);

		boolean isNameNull = (name == null) || (name.length() == 0);
		boolean isUserNull = (userName == null) || (userName.length() == 0);
		boolean isExpireDttmNull = (expireDttm == null) || (expireDttm.length() == 0);
		if (curPage == 0)
			curPage = 1;
		int totalCount = 0;

		// 如果有name，那么唯一检索
		if (!isNameNull) {
			System.out.println("name唯一检索");
			curPage = 1;
			totalPage = 1;
			totalCount = (int) service.getCountByName(name);
			if (totalCount % pageSize == 0)
				totalPage = totalCount / pageSize;
			else
				totalPage = totalCount / pageSize + 1;
			this.topics = service.getAllByName((curPage - 1) * pageSize, pageSize, name);
		} else {
			// 没有任何检索条件
			if (isUserNull && isExpireDttmNull) {
				System.out.println("没有检索条件");
				totalCount = (int) service.getCount();
				if (totalCount % pageSize == 0)
					totalPage = totalCount / pageSize;
				else
					totalPage = totalCount / pageSize + 1;
				this.topics = service.getAll((curPage - 1) * pageSize, pageSize);
			}
			// 只有user检索条件
			else if (!isUserNull && isExpireDttmNull) {
				System.out.println("只按照用户名来检索");
				System.out.println("userName:" + userName);
				User searchUser = userService.getByLoginName(userName);
				System.out.println("searchUser:" + searchUser);
				if (searchUser != null) {
					List<UserTopic> uts = userTopicService.getUserTopicsByUserId(searchUser.getId());
					// 如果该用户有订阅的主题
					topics = new ArrayList<Topic>();
					if (uts.size() != 0) {
						for (UserTopic ut : uts) {
							topics.add(ut.getTopic());
						}
						totalCount = topics.size();
						if (totalCount % pageSize == 0)
							totalPage = totalCount / pageSize;
						else
							totalPage = totalCount / pageSize + 1;
					}
				}
			}
			// 只有expireDttm检索条件
			else if (isUserNull && !isExpireDttmNull) {
				System.out.println("只按照时间来检索");
				totalCount = (int) service.getCountByExpireDttm(expireDttm);
				if (totalCount % pageSize == 0)
					totalPage = totalCount / pageSize;
				else
					totalPage = totalCount / pageSize + 1;
				this.topics = service.getAllByExpireDttm((curPage - 1) * pageSize, pageSize, expireDttm);
			}

			// user和exipreDttm都是检索条件
			else {
				System.out.println("按照用户名，时间来检索");
				System.out.println("只按照用户名来检索");
				System.out.println("userName:" + userName);
				User searchUser = userService.getByLoginName(userName);
				System.out.println("searchUser:" + searchUser);
				if (searchUser != null) {
					List<UserTopic> uts = userTopicService.getUserTopicsByUserId(searchUser.getId());
					// 如果该用户有订阅的主题
					topics = new ArrayList<Topic>();
					if (uts.size() != 0) {
						// 是user的topics，也是符合时间的topics
						for (UserTopic ut : uts) {
							String dbExpireDttm = ut.getTopic().getExpireDttm().substring(0, 10);
							System.out.println("input time:" + expireDttm);
							System.out.println("db time:" + dbExpireDttm);
							if (expireDttm.equals(dbExpireDttm))
								topics.add(ut.getTopic());
						}
						totalCount = topics.size();
						if (totalCount % pageSize == 0)
							totalPage = totalCount / pageSize;
						else
							totalPage = totalCount / pageSize + 1;
					}
				}
			}
		}
		if (topics != null)
			System.out.println("topic count:" + this.topics.size());
		System.out.println("curPage:" + curPage);
		System.out.println("totalCount:" + totalCount);

		return Action.SUCCESS;
	}

	public String addTopic() {
		service.addTopic("hello xxx");
		return listTopic();
	}

	public String deleteTopic() {
		System.out.println("delete topic:");
		for (int i = 0; i < this.delIds.size(); i++) {
			System.out.println("deleted ids：" + delIds.get(i));
			long topicId = Long.parseLong(delIds.get(i));

			// 级联的warn也得删除
			List<Warn> warns = warnService.getWarnsByTopicId(topicId);
			for (Warn warn : warns) {
				warnService.delete(warn.getId());
			}
			// 删除级联的user_topic
			List<UserTopic> userTopics = userTopicService.getUserTopicsByTopicId(topicId);
			for (UserTopic userTopic : userTopics) {
				userTopicService.delete(userTopic.getId());
			}
			// 删除topic
			service.delete(topicId);
		}
		return "topicDeleted";
	}

	// 新建话题
	public String saveTopic() {
		System.out.println("name:" + name);
		// System.out.println("sourceCategory:" + sourceCategory);
		System.out.println(description);
		System.out.println(include);
		System.out.println(optional);
		System.out.println(exclude);
		System.out.println(isNegative);
		System.out.println(isWarn);
		System.out.println(expireDttm);
		System.out.println(withinPublishedTime);

		// 添加topic表
		Topic topic = new Topic();
		topic.setName(name);
		topic.setDescription(description);
		topic.setInclude(include);
		topic.setOptional(optional);
		topic.setExclude(exclude);
		topic.setIsNegative(isNegative);
		topic.setIsWarn(isWarn);
		topic.setExpireDttm(expireDttm);
		topic.setWithinPublishedTime(withinPublishedTime);
		topic.setUpdateDttm(new Date());
		service.addTopic(topic);

		// 添加topic_source表
		TopicSource ts = new TopicSource();
		ts.setCatagoryName(sourceCategoryName);// ????
		ts.setTopic(topic);
		ts.setSource(sourceService.getById(0));// TODO:source哪里输入的？？？

		topicSourceService.addTopicSource(ts);

		return "saveTopic";
	}

	public String searchTopic() {
		System.out.println("search topic");
		System.out.println("name:" + name);
		System.out.println("userName:" + userName);
		System.out.println("expireDttm:" + expireDttm);

		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();

		// 清除旧的检索条件
		session.remove("topicName");
		session.remove("topicaUserName");
		session.remove("topicExpireDttm");

		// 保存当前的检索条件
		session.put("topicName", name);
		session.put("topicUserName", userName);
		session.put("topicExpireDttm", expireDttm);

		return "searchTopic";
	}

	// 显示编辑的页面
	public String editTopic() {
		System.out.println("edit topic:" + topicId);
		Topic t = service.getById(topicId);
		name = t.getName();
		description = t.getDescription();
		include = t.getInclude();
		optional = t.getOptional();
		exclude = t.getExclude();
		isNegative = t.getIsNegative();
		isWarn = t.getIsWarn();
		if (t.getExpireDttmStr() != null)
			expireDttm = t.getExpireDttmStr();
		else
			expireDttm = "";
		withinPublishedTime = t.getWithinPublishedTime();
		// 从topic source表load媒体分组名称
		List<TopicSource> tss = topicSourceService.getByTopicId(topicId);
		sourceCategoryName = tss.get(0).getCatagoryName();
		return Action.SUCCESS;
	}

	public String updateTopic() {
		System.out.println("update topic");
		System.out.println("topicId:" + topicId);
		System.out.println("name:" + name);
		System.out.println("selectedSourceCategory:" + this.selectedSourceCategory);
		System.out.println("desc:" + description);
		System.out.println("inc" + include);
		System.out.println("opt:" + optional);
		System.out.println("excl:" + exclude);
		System.out.println("isNegative:" + this.selectedIsNegative);
		System.out.println("isWarn:" + this.selectedIsWarn);
		System.out.println("exp:" + expireDttm);
		System.out.println("withinPublishedTime:" + this.selectedWithinPublishedTime);

		// 修改topic表的内容
		Topic topic = service.getById(topicId);
		topic.setName(name);
		topic.setDescription(description);
		topic.setInclude(include);
		topic.setOptional(optional);
		topic.setExclude(exclude);
		topic.setIsNegative(Integer.parseInt(this.selectedIsNegative));
		topic.setIsWarn(Integer.parseInt(this.selectedIsWarn));
		topic.setExpireDttm(expireDttm);
		topic.setUpdateDttm(new Date());
		topic.setWithinPublishedTime(Integer.parseInt(selectedWithinPublishedTime));

		// 修改topic_source表的内容
		List<TopicSource> topicSources = topicSourceService.getByTopicId(topicId);
		for (TopicSource ts : topicSources) {
			ts.setCatagoryName(selectedSourceCategory);
			topicSourceService.update(ts);
		}

		System.out.println("topic set");
		// SourceCategory sc =
		// sourceCategoryService.getById(Integer.parseInt(selectedSourceCategory));
		// System.out.println("sc:" + sc.getId());
		// topic.setSourceCategory(sc);
		System.out.println("topic set");

		service.update(topic);
		System.out.println("update okok~");
		return "updateTopic";
	}

	public List<Topic> getTopics() {
		return topics;
	}

	public void prepare() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		String username = (String) session.get("username");
		curUser = userService.getByLoginName(username);
		System.out.println("curUser.getLoginName():" + curUser.getLoginName());

		// 查询所有的类型
		List<SourceCategory> tmp = sourceCategoryService.getAllSourceCategories();
		filters = new ArrayList<SourceCategory>();
		System.out.println("source category count:" + tmp.size());

		names = new ArrayList<String>();
		// 投影name到filters上
		for (SourceCategory sc : tmp) {
			String name = sc.getName();
			if (!names.contains(name)) {
				names.add(name);
				filters.add(sc);
			}
		}

		System.out.println("多少个类别:" + filters.size());

	}

	public void setTopicService(TopicService service) {
		this.service = service;
	}

	public ArrayList<String> getDelIds() {
		return delIds;
	}

	public void setDelIds(ArrayList<String> delIds) {
		this.delIds = delIds;
	}

	public void setService(TopicService service) {
		this.service = service;
	}

	public void setTopics(List<Topic> topics) {
		this.topics = topics;
	}

	public String getInclude() {
		return include;
	}

	public void setInclude(String include) {
		this.include = include;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getIsWarn() {
		return isWarn;
	}

	public void setIsWarn(int isWarn) {
		this.isWarn = isWarn;
	}

	public int getIsNegative() {
		return isNegative;
	}

	public void setIsNegative(int isNegative) {
		this.isNegative = isNegative;
	}

	public void setWarnService(WarnService warnService) {
		this.warnService = warnService;
	}

	public void setUserTopicService(UserTopicService userTopicService) {
		this.userTopicService = userTopicService;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getOptional() {
		return optional;
	}

	public void setOptional(String optional) {
		this.optional = optional;
	}

	public String getExclude() {
		return exclude;
	}

	public void setExclude(String exclude) {
		this.exclude = exclude;
	}

	public String getExpireDttm() {
		return expireDttm;
	}

	public void setExpireDttm(String expireDttm) {
		this.expireDttm = expireDttm;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public void setSourceCategoryService(SourceCategoryService sourceCategoryService) {
		this.sourceCategoryService = sourceCategoryService;
	}

	public List<SourceCategory> getSourceCategories() {
		return sourceCategories;
	}

	public void setSourceCategories(List<SourceCategory> sourceCategories) {
		this.sourceCategories = sourceCategories;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getCurUser() {
		return curUser;
	}

	public void setCurUser(User curUser) {
		this.curUser = curUser;
	}

	public int getTopicId() {
		return topicId;
	}

	public void setTopicId(int topicId) {
		this.topicId = topicId;
	}

	public String getSourceCategoryName() {
		return sourceCategoryName;
	}

	public void setSourceCategoryName(String sourceCategoryName) {
		this.sourceCategoryName = sourceCategoryName;
	}

	// public long getSourceCategory() {
	// return sourceCategory;
	// }
	//
	// public void setSourceCategory(long sourceCategory) {
	// this.sourceCategory = sourceCategory;
	// }

	public String getSelectedSourceCategory() {
		return selectedSourceCategory;
	}

	public void setSelectedSourceCategory(String selectedSourceCategory) {
		this.selectedSourceCategory = selectedSourceCategory;
	}

	public String getSelectedIsWarn() {
		return selectedIsWarn;
	}

	public void setSelectedIsWarn(String selectedIsWarn) {
		this.selectedIsWarn = selectedIsWarn;
	}

	public String getSelectedIsNegative() {
		return selectedIsNegative;
	}

	public void setSelectedIsNegative(String selectedIsNegative) {
		this.selectedIsNegative = selectedIsNegative;
	}

	public List<String> getNames() {
		return names;
	}

	public void setNames(List<String> names) {
		this.names = names;
	}

	public ArrayList<SourceCategory> getFilters() {
		return filters;
	}

	public void setFilters(ArrayList<SourceCategory> filters) {
		this.filters = filters;
	}

	public int getWithinPublishedTime() {
		return withinPublishedTime;
	}

	public void setWithinPublishedTime(int withinPublishedTime) {
		this.withinPublishedTime = withinPublishedTime;
	}

	public String getSelectedWithinPublishedTime() {
		return selectedWithinPublishedTime;
	}

	public void setSelectedWithinPublishedTime(String selectedWithinPublishedTime) {
		this.selectedWithinPublishedTime = selectedWithinPublishedTime;
	}

	public void setTopicSourceService(TopicSourceService topicSourceService) {
		this.topicSourceService = topicSourceService;
	}

	public void setSourceService(SourceService sourceService) {
		this.sourceService = sourceService;
	}

}